<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2022/12/26
 * Time: 1:26 PM
 */

namespace app\api\controller\v36;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Goods;
use app\common\cachemodel\OrdersLib;
use app\common\lib\astrolog\Acg;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\FateCity;
use app\common\model\Map as MapModel;
use app\common\model\Recode;
use think\Cache;
use think\Env;
use think\exception\DbException;

class Map extends Auth
{

    protected static $oss;

    public function _initialize()
    {
        parent::_initialize();
        self::$oss = Env::get('host.photo');
    }

    /**
     * ACG地点详情
     * @return \think\response\Json
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $type = input('get.type');// 地点类型

        $rid = input('get.rid');// 档案id

        if (!$rid) return show(config('code.error'), '档案不存在');

        $current_longitude = input('get.current_longitude');// 所在位置经纬度

        $current_latitude = input('get.current_latitude');// 所在位置经纬度

        $point_longitude = input('get.point_longitude');// 选择点的经纬度

        $point_latitude = input('get.point_latitude');// 选择点的经纬度

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];

        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $info = [
            'type' => $type,// 1=>普通地点，2=>命运之地
            'rid' => $rid,// 档案id
            'current_longitude' => $current_longitude,// 当前所在位置经度
            'current_latitude' => $current_latitude,// 当前所在位置纬度
            'point_longitude' => $point_longitude,// 选择的点的经度
            'point_latitude' => $point_latitude,// 选择的点的纬度
            'longitude' => $longitude,// 用户出生地经度
            'latitude' => $latitude,// 用户出生地纬度
            'time' => $timestamp,// 用户出生时间
            'sex' => $recode['type'],// 档案性别
            'isself' => $recode['isself'],// 当前档案是否为自己，检查是否有赠送记录，计算命格线对地点的影响
            'uid' => $this->user['id'],// 用户id
        ];

        $validate = validate('Map');

        if (!$validate->scene('read')->check($info)) return show(config('code.error'), (string)$validate->getError());
        // 获取选中地点分值
        $array = (new Acg())->getRecommendedInfo2($info);
        // 获取选中地点收藏状态
        $collect_status = (new MapModel())->checkCollectStatus(['latitude' => $point_latitude, 'longitude' => $point_longitude, 'uid' => $this->user['id'], 'rid' => $rid]);

        $array['is_collect'] = $collect_status['is_collect'];
        $array['collect_id'] = $collect_status['collect_id'];

        if ($type == 2) $array['type'] = true;

        //获取当前档案解锁的商品
        $goods = (new Goods())->GoodsTypeInfo(5);
        $goods_gids = array_column($goods, 'id');
        $unlcok_goods = OrdersLib::CheckPayGids($this->user['id'], $rid, 5, $goods_gids, $rid);//当前档案所有已解锁的GID
        // 获取当前城市距离最近的命格线类型和城市指数类型
        $linePointXy = $this->getLinePointXy($recode);
        $nearestLineDes = $this->getNearestLineName($point_longitude, $point_latitude, $linePointXy);

        $array['top_hint_list'] = [
            [
                'icon' => self::$oss . 'test/map/city_score/line_icon.png',
                'title' => '命格线',
                'des' => $nearestLineDes,
                'tips' => (new MapModel())->getLineUnlockStatus($unlcok_goods['gids']) ? '' : '了解更多影响',
                'type' => 1,
                'alert_title' => '- 命格线 -',
                'alert_content' => '这里一共包含11条命格线，包含我们免费赠送的梦想线、变革线。每条命格线经过的地方都对你有特殊影响。
解锁后所有的命格线会在地图上展示，每条线都会有详细的解释和使用方法介绍。',
            ]
        ];
        if (!(new MapModel())->getCityScoreUnlockStatus($unlcok_goods['gids']))
        {
            array_multisort(array_column($array['specific_impact'], 'score'), SORT_NUMERIC, SORT_DESC, $array['specific_impact']);// 按 score 排序
            $array['top_hint_list'][] = [
                'icon' => self::$oss . 'test/map/city_score/city_score_icon.png',
                'title' => '指数排行',
                'des' => "你在[city_name]的{$array['specific_impact'][0]['title']}指数还不错，快去看看排行",
                'tips' => '了解更多影响',
                'type' => 2,
                'alert_title' => '- 城市指数排行 -',
                'alert_content' => '这里一共包含9大维度的指数排行。
包含：幸运指数、健康指数、事业指数、财富指数、桃花指数、安居指数、社交指数、游乐指数、知识指数
解锁后你可以查看任意城市范围内的不同维度的指数排行情况，了解在不同地点对你的不同影响',
            ];
        }
        //获取当前城市的具体影响
        array_walk($array['specific_impact'], static function (&$v)
        {
            switch ($v['title'])
            {
                case '财富':
                    $v['icon'] = self::$oss . 'test/map/city_score/icon_5.png';
                    break;
                case '工作':
                    $v['icon'] = self::$oss . 'test/map/city_score/icon_3.png';
                    break;
                case '婚恋':
                    $v['icon'] = self::$oss . 'test/map/city_score/icon_10.png';
                    break;
                case '健康':
                    $v['icon'] = self::$oss . 'test/map/city_score/icon_2.png';
                    break;
                case '学习':
                    $v['icon'] = self::$oss . 'test/map/city_score/icon_8.png';
                    break;
                case '幸运':
                    $v['icon'] = self::$oss . 'test/map/city_score/icon_1.png';
                    break;
                default:
                    $v['icon'] = '';
            }
        });
        $array['specific_impact'] = [
            'status' => (new MapModel())->getAnywhereUnlockStatus($unlcok_goods['gids']),
            'items' => $array['specific_impact']
        ];
        return show(config('code.success'), '加载成功', $array);
    }

    /**
     * 命格线列表
     * @return \think\response\Json
     * @throws ApiException
     */
    public function lines_list()
    {
        $rid = input('rid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '档案不存在');
        }
        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }
        $mapModel = new MapModel();
        //获取用户当前已解锁的数据
        $unlockInfo = $mapModel->getRecodeUnlockLines($recode, true);
        $lines = $unlockInfo['lines'];
        $arr['lines_list'] = $mapModel->getLineList($this, $lines['data'], true);// 所有命格线商品
        $lineStatus = $mapModel->getLineUnlockStatus($unlockInfo['unlock_gids']);
        if (!$lineStatus)
        {
            $arr['tips_info'] = [
                'tip1' => '超值解锁所有命格线',
                'tip2' => '99元解锁',
                'alert_title' => '- 命格线 -',
                'alert_content' => '这里一共包含11条命格线，包含我们免费赠送的梦想线、变革线。每条命格线经过的地方都对你有特殊影响。
解锁后所有的命格线会在地图上展示，每条线都会有详细的解释和使用方法介绍。',
            ];
        }
        return show(config('code.success'), '获取成功', $arr);
    }

    /**
     * 获取城市排行信息
     * @return \think\response\Json
     * @throws \Exception
     */
    public function cityList()
    {
        $rid = input('rid/d', 0);
        $type = input('type/d', 1);
        $cid = input('cid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '档案不存在');
        }
        if (!$type)
        {
            return show(config('code.error'), '未知的类型');
        }
        if (!$cid)
        {
            $cid = 100000;
        }
        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }
        $config = array_column(config('map.city_score'), null, 'gid');
        $config2 = array_column(config('map.city_score'), null, 'type');
        $mapModel = new MapModel();
        //获取用户当前已解锁的数据
        $unlockInfo = $mapModel->getRecodeUnlockLines($recode, true);
        $cityScoreStatus = $mapModel->getCityScoreUnlockStatus($unlockInfo['unlock_gids']);
        $isUnlock = 0;
        //打包解锁
        if ($cityScoreStatus)
        {
            $isUnlock = 1;
            array_walk($config, static function (&$v, $k, $p)
            {
                $v = array_merge($v, $p);
            }, ['status' => 1]);
        } else//当前类型是否已解锁
        {
            if (in_array($config2[$type]['gid'], $unlockInfo['unlock_gids'], false))
            {
                $isUnlock = 1;
            }
            array_walk($config, static function (&$v, $k, $p)
            {
                $v = array_merge($v, $p);
            }, ['status' => 0]);
            foreach ($unlockInfo['unlock_gids'] as $gid)
            {
                if (!empty($config[$gid]))
                {
                    $config[$gid]['status'] = 1;
                }
            }
            $arr = [
                'tips_info' => [
                    'tip1' => '超值解锁所有指数排行',
                    'tip2' => '69元解锁',
                    'alert_title' => '- 城市指数排行 -',
                    'alert_content' => '这里一共包含9大维度的指数排行。
包含：幸运指数、健康指数、事业指数、财富指数、桃花指数、安居指数、社交指数、游乐指数、知识指数
解锁后你可以查看任意城市范围内的不同维度的指数排行情况，了解在不同地点对你的不同影响',
                ]
            ];
        }
        //获取城市排行数据
        $arr['city_list'] = $this->getCityData($this->user['id'], $type, $cid, $recode, $isUnlock);
        $arr['tag_list'] = array_values($config);
        if ($isUnlock)
        {
            $arr['btn_info'] = null;
        } else
        {
            $arr['btn_info'] = [
                'name' => "解锁{$config2[$type]['name']}指数排行",
                'target' => 'local',
                'link' => "pay_order?type=5&gid={$config2[$type]['gid']}&rid={$rid}"
            ];
            $arr['city_list'] = array_slice($arr['city_list'], 0, 6);
        }
        return show(config('code.success'), '获取成功', $arr);
    }

    /**
     * 获取命运之城列表
     * @return \think\response\Json
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fateCityList()
    {
        $rid = input('rid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '档案不存在');
        }
        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }
        $mapModel = new MapModel();
        //获取用户当前已解锁的数据
        $unlockInfo = $mapModel->getRecodeUnlockLines($recode, true);
        $fateCityStatus = $mapModel->getFateCityUnlockStatus($unlockInfo['unlock_gids']);
        if ($fateCityStatus)
        {
            if ($unlockInfo['lines']['status'] == 2)
            {
                $arr['pop_info'] = [
                    'content' => '这是在中国境内，对你生活起居某方面最为有利的大城市，能对你不同方面起到良好的改善的作用。（此处只有国内一、二、三线城市，后续会持续更新国内其他小城市和国外城市的计算，所以你的命运之城可能会随着升级会有改变）。解锁后对每一座命运之城都有详细解读。',
                    'btn_title' => '计算中',
                    'status' => 1
                ];
            } else
            {
                $info = [
                    'uid' => (int)$this->user['id'],
                    'rid' => $rid,// 档案id
                    'sex' => $recode['type'],// 档案性别
                    'isself' => $recode['isself'],
                    'longitude' => ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'],// 用户出生地经度
                    'latitude' => ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'],// 用户出生地纬度
                    'time' => strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute'])
                        - ($recode['timezone'] + $recode['is_summer']) * 3600,// 用户出生时间
                ];
                $fate_city = (new FateCity())->getUserFateCitys($info);
                $tmp = [];
                $fateCityConfig = config('map');
                $fateCityName = array_flip($fateCityConfig['fate_city_name']);
                foreach ($fate_city as $value)
                {
                    $fateName = explode('、', $value['name']);
                    foreach ($fateName as $key => $item)
                    {

                        $tmp[] = [
                            'id' => $fateCityName[$item],
                            'name' => $item,
                            'icon' => $fateCityConfig['fate_city'][$fateCityName[$item]],
                            'des' => $fateCityConfig['fate_city_des'][$fateCityName[$item]],
                            'longitude' => $value['longitude'],
                            'latitude' => $value['latitude'],
                        ];
                    }
                }
                sort($tmp);
                array_unshift($tmp, [
                    'id' => 10,
                    'name' => $fateCityConfig['lines_name'][18],
                    'icon' => $fateCityConfig['lines_icon'][18],
                    'des' => $fateCityConfig['lines_des'][18]
                ]);
                $arr['city_list'] = $tmp;
            }
        } else
        {
            $arr['pop_info'] = [
                'content' => '这是在中国境内，对你生活起居某方面最为有利的大城市，能对你不同方面起到良好的改善的作用。（此处只有国内一、二、三线城市，后续会持续更新国内其他小城市和国外城市的计算，所以你的命运之城可能会随着升级会有改变）。解锁后对每一座命运之城都有详细解读。',
                'btn_title' => '39元解锁命运之城',
                'status' => 0
            ];
        }
        return show(config('code.success'), '获取成功', $arr);
    }

    /**
     * @throws \Exception
     */
    protected function getCityData($uid, $type, $cid, $recode, $isUnlock)
    {
        $mapCity = config('map_city')[$cid];
        if (count($mapCity['children']) > 10)
        {
            $cityScore = Cache::get(FateCity::$scoreCity . $recode['id'] . '-' . $cid);
        } else
        {
            $cityScore = false;
        }
        if (!$cityScore)
        {
            $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

            $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

            $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];

            $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

            array_walk($mapCity['children'], static function (&$v) use ($uid, $longitude, $recode, $latitude, $timestamp)
            {
                $info = [
                    'rid' => $recode['id'],
                    'uid' => $uid,
                    'point_longitude' => $v['longitude'],// 选择的点的经度
                    'point_latitude' => $v['latitude'],// 选择的点的纬度
                    'longitude' => $longitude,// 用户出生地经度
                    'latitude' => $latitude,// 用户出生地纬度
                    'time' => $timestamp,// 用户出生时间
                    'sex' => $recode['type'],// 档案性别
                    'isself' => $recode['isself'],// 当前档案是否为自己，检查是否有赠送记录，计算命格线对地点的影响
                    'city_score_type' => [0, 1, 2, 3, 4, 5, 6, 7, 8],//城市排行指数  0养生 1工作 2学习 3旅游 4定居 5婚恋 6财富 7社交 8幸运
                ];
                $v['city_score_info'] = (new Acg())->getRecommendedInfo2($info);
            });
            $cityScore = $mapCity['children'];
            Cache::set(FateCity::$scoreCity . $recode['id'] . '-' . $cid, $cityScore, 7200);
        }
        $typeIndex = [
            1 => 8,
            2 => 0,
            3 => 1,
            4 => 5,
            5 => 6,
            6 => 3,
            7 => 4,
            8 => 2,
            9 => 7,
        ];
        $fateCityIndex = -1;
        $config = array_column(config('map.city_score'), null, 'type');
        $data = $config[$type];
        foreach ($cityScore as $key => $item)
        {
            $cityScore[$key]['score'] = $item['city_score_info']['city_score'][$typeIndex[$type]];
            if (in_array($data['fcid'] + 1, $item['city_score_info']['fcid'], true))
            {
                $fateCityIndex = $key;
            }
        }
        $scoreArr = array_column($cityScore, 'score');
        $maxScore = max($scoreArr);
        if ($fateCityIndex !== -1)
        {
            $score = $maxScore + 1;
            $cityScore[$fateCityIndex]['score'] = min($score, 99);
        }

        array_multisort(array_column($cityScore, 'score'), SORT_NUMERIC, SORT_DESC, $cityScore);// 按 score 排序

        $res = [];
        foreach ($cityScore as $key => $item)
        {
            $item = array_merge($item, $data);
            $item['tag_icon'] = '';
            $item['img'] = '';
            $typeTmp = 2;
            if ($isUnlock)
            {
                $item['tag_icon'] = in_array($data['fcid'] + 1, $item['city_score_info']['fcid'], true) ? self::$oss . "test/map/city_score/tag_icon_{$type}.png" : '';
                //因客户端弄错字段,特殊处理
                if (isset($this->headers['channel']) && stripos($this->headers['channel'], 'vivo') !== false && Util::CheckAppVersion('2.9.6') === '同')
                {
                    $item['img'] = $item['tag_icon'];
                }
            } elseif (in_array($key, [0, 1, 2], true))
            {
                $typeTmp = 1;
            }
            $item['name'] = $item['text'];
            $item['text'] = $item['city_score_info']['fate_city_name'] ?? '';
            unset($item['city_score_info']);
            $item['type'] = $typeTmp;

            $res[] = $item;
        }
        if (!$isUnlock)
        {
            $res[0]['img'] = self::$oss . "test/map/city_score/shade/{$type}-1.png";
            $res[1]['img'] = self::$oss . "test/map/city_score/shade/{$type}-2.png";
            $res[2]['img'] = self::$oss . "test/map/city_score/shade/{$type}-3.png";
        }
        return $res;
    }

    /**
     * 获取 地图 国内划线坐标信息
     * @return array
     */
    protected function getLinePointXy(array $recodeInfo)
    {
//        $planets = (new Acg())->getPlanetInfo($recodeInfo);// 计算客户端绘制命格线所需的数据
        $unlockInfo = (new MapModel())->getRecodeUnlockLines($recodeInfo, true);
        $planets = $unlockInfo['planets'];// 计算客户端绘制命格线所需的数据
        //***************计算绘制线和点的数据************************
        $planet1 = $planets['planet1'];
        $planet2 = $planets['planet2'];
        $lon = ($recodeInfo['long_deg'] + $recodeInfo['long_min'] / 60) * $recodeInfo['ew'];
        $MC = 20;
        $longm = $this->Mod($planet1[$MC] - $lon); // 天顶的赤经 - 用户经度
        $lat_max = 90; // 最大纬度值
        $lat_min = -90; // 最小纬度值
        $degToRadian = 180 / M_PI; // 角度转弧度

        $optionsMC = [];
        $optionsIC = [];
        $optionsASC = [];
        $optionsASC2 = [];
        $optionsDES = [];
        $optionsDES2 = [];
        // 需要绘制的线有 日0月1水2金3火4木5土6天7海8冥9 北交点12   总共11个行星
        foreach ($planet1 as $i => $p)
        {
            if ($i >= 17) break;
            //******* 行星-天顶 垂直线 *******
            $x1 = $this->Mod($planet1[$i] + $lon - $planet1[$MC]); // 行星赤经 + 用户经度 - 天顶赤经值
            $optionsMC[$i]['path'] = [
                [$x1, $lat_min],
                [$x1, $lat_max]
            ]; // 垂直线的起点x1,y1和终点x2,y2
            //******* 行星-天顶 垂直线 *******


            //******* 行星-天底 垂直线 *******
            // 行星-天底 垂直线
            $x2 = $this->Mod($x1 + 180); // 行星赤经 + 用户经度 + 180 - 天顶赤经值
            $optionsIC[$i]['path'] = [
                [$x2, $lat_min],
                [$x2, $lat_max]
            ]; // 垂直线的起点x1,y1和终点x2,y2
            //******* 行星-天底 垂直线 *******

            $xold1 = -1000;
            $xold2 = -1000; // 初始化
            $pathASC = [];
            $pathASC2 = [];
            $pathDES = [];
            $pathDES2 = [];
            for ($lat = $lat_min; $lat <= $lat_max; $lat += 0.06)
            {
                // console.log("循环开始 lat:"+lat);
                // 行星i的弧度（赤纬值转为弧度）正切值 * 当前循环弧度（纬度转为弧度）正切值
                // 资料来源： https://baike.baidu.com/item/Tan/14821216?fr=aladdin
                // 以下为基于直角三角形
                // 正切：把∠A的对边与邻边的比叫做∠A的正切（tangent），记作tanA
                // tanA=sinA/cosA
                $ad = asin(tan($planet2[$i] / $degToRadian) * tan($lat / $degToRadian));
                $z = $this->Mod($planet1[$i] - $ad * $degToRadian - 90 - $longm);
                if (!is_nan($z))
                {
                    if (($xold1 !== -1000 && $xold1 * $z < 0) || count($pathASC2) > 0)
                    {
                        if ($z >= 73 && $z <= 135 && $lat >= 18 && $lat <= 55)
                        {
                            array_push($pathASC2, [$z, $lat]);
                        }
                    } else
                    {
                        if ($z >= 73 && $z <= 135 && $lat >= 18 && $lat <= 55)
                        {
                            array_push($pathASC, [$z, $lat]);
                        }
                    }
                    $xold1 = $z;
                }
                $z = $this->Mod($planet1[$i] + $ad * $degToRadian + 90 - $longm);
                if (!is_nan($z))
                {
                    if (($xold2 !== -1000 && $xold2 * $z < 0) || count($pathDES2) > 0)
                    {
                        if ($z >= 73 && $z <= 135 && $lat >= 18 && $lat <= 55)
                        {
                            array_push($pathDES2, [$z, $lat]);
                        }
                    } else
                    {
                        if ($z >= 73 && $z <= 135 && $lat >= 18 && $lat <= 55)
                        {
                            array_push($pathDES, [$z, $lat]);
                        }
                    }
                    $xold2 = $z;
                }
            }
            //******开始绘制上升线******
            $optionsASC[$i]['path'] = $pathASC;
            $optionsASC2[$i]['path'] = $pathASC2;
            //******开始绘制上升线******


            //******开始绘制下降线******
            $optionsDES[$i]['path'] = $pathDES;
            $optionsDES2[$i]['path'] = $pathDES2;
            //******开始绘制下降线******
        }
        //***************计算绘制线和点的数据************************


        $resData = [
            'optionsMC' => $optionsMC,
            'optionsIC' => $optionsIC,
            'optionsASC' => $optionsASC,
            'optionsASC2' => $optionsASC2,
            'optionsDES' => $optionsDES,
            'optionsDES2' => $optionsDES2,
        ];

        return $resData;
    }

    // Mod函数实现 地图经度为-180～180度 西经180度到东经180度
    private function Mod($d)
    {
        $d -= floor($d / 360) * 360;

        if ($d >= 180) $d -= 360;

        else if ($d < -180) $d += 360;

        return $d;
    }

    /**
     * 获取 当前位置 与线最近距离
     * @return string
     */
    protected function getNearestLineName($longitude, $latitude, array $pointXyData)
    {
        $nearestData = [];
        //******* 行星-天顶 垂直线 取最近距离 *******
        foreach ($pointXyData['optionsMC'] as $pid => $optionsMCItem)
        {
            if (isset($optionsMCItem['path'][0][0]))
            {
                $longMC1 = $optionsMCItem['path'][0][0];
                $len = $this->getPointLength($longitude, $latitude, $longMC1, $latitude);
                if (empty($nearestData) || ($nearestData && $nearestData['len'] > $len))
                {
                    $nearestData = [
                        'pid' => $pid,
                        'len' => $len,
                        'text' => 'Ⅱ'
                    ];
                }
            }
        }
        //******* 行星-天底 垂直线 *******
        foreach ($pointXyData['optionsIC'] as $pid => $optionsICItem)
        {
            if (isset($optionsICItem['path'][0][0]))
            {
                $longIC1 = $optionsICItem['path'][0][0];
                $len = $this->getPointLength($longitude, $latitude, $longIC1, $latitude);
                if (empty($nearestData) || ($nearestData && $nearestData['len'] > $len))
                {
                    $nearestData = [
                        'pid' => $pid,
                        'len' => $len,
                        'text' => 'Ⅳ'
                    ];
                }
            }
        }
        //******绘制上升线 取最近距离******
        foreach ($pointXyData['optionsASC'] as $pid => $optionsASCItem)
        {
            foreach ($optionsASCItem['path'] as $pathItem)
            {
                $len = $this->getPointLength($longitude, $latitude, $pathItem[0], $pathItem[1]);
                if (empty($nearestData) || ($nearestData && $nearestData['len'] > $len))
                {
                    $nearestData = [
                        'pid' => $pid,
                        'len' => $len,
                        'text' => 'Ⅰ'
                    ];
                }
            }
        }
        foreach ($pointXyData['optionsASC2'] as $pid => $optionsASC2Item)
        {
            foreach ($optionsASC2Item['path'] as $pathItem)
            {
                $len = $this->getPointLength($longitude, $latitude, $pathItem[0], $pathItem[1]);
                if (empty($nearestData) || ($nearestData && $nearestData['len'] > $len))
                {
                    $nearestData = [
                        'pid' => $pid,
                        'len' => $len,
                        'text' => 'Ⅰ'
                    ];
                }
            }
        }
        //******绘制下降线 取最近距离******
        foreach ($pointXyData['optionsDES'] as $pid => $optionsItem)
        {
            foreach ($optionsItem['path'] as $pathItem)
            {
                $len = $this->getPointLength($longitude, $latitude, $pathItem[0], $pathItem[1]);
                if (empty($nearestData) || ($nearestData && $nearestData['len'] > $len))
                {
                    $nearestData = [
                        'pid' => $pid,
                        'len' => $len,
                        'text' => 'Ⅲ'
                    ];
                }
            }
        }
        foreach ($pointXyData['optionsDES2'] as $pid => $optionsItem)
        {
            foreach ($optionsItem['path'] as $pathItem)
            {
                $len = $this->getPointLength($longitude, $latitude, $pathItem[0], $pathItem[1]);
                if (empty($nearestData) || ($nearestData && $nearestData['len'] > $len))
                {
                    $nearestData = [
                        'pid' => $pid,
                        'len' => $len,
                        'text' => 'Ⅲ'
                    ];
                }
            }
        }

        $lineNameConfig = [
            0 => "[city_name]距离你的成就线{$nearestData['text']}最近，这是你的“事业补给站”，靠近这里会有好事发生哦！",
            1 => "[city_name]距离你的安居线{$nearestData['text']}最近，也是离人间烟火最近的地方，适合放慢脚步、享受生活~",
            2 => "[city_name]距离你的智慧线{$nearestData['text']}最近，在这里没有“水逆”一说，学习考试通通过！",
            3 => "[city_name]距离你的桃花线{$nearestData['text']}最近，一个让你迅速脱单，摆脱七大姑八大姨夺命连环催的好地方。",
            4 => "[city_name]距离你的激情线{$nearestData['text']}最近，负能量过剩时来这里走一走，又是人间小太阳！",
            5 => "[city_name]距离你的幸运线{$nearestData['text']}最近，幸运buff不断叠加的地方，一定要多去几趟！",
            6 => "[city_name]距离你的成长线{$nearestData['text']}最近，来过的都不想再来，但多年以后又心怀感恩。",
            7 => "[city_name]距离你的变革线{$nearestData['text']}最近，潘多拉的魔盒已开启，下一秒是惊是喜谁也不知道。",
            8 => "[city_name]距离你的梦想线{$nearestData['text']}最近，靠近这里，你就再也不是一条没有梦想的咸鱼啦！",
            9 => "[city_name]距离你的生死线{$nearestData['text']}最近，关于你人生的风雨，都在这里倾盆而下。",
            12 => "[city_name]距离你的宿命线{$nearestData['text']}最近，在与命运交汇的地方，总能领悟些什么。",
        ];

        return $lineNameConfig[$nearestData['pid']];
    }

    /**
     * 获取两点间的距离
     * @return float
     */
    protected function getPointLength($x1, $y1, $x2, $y2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($y1 * pi()) / 180;
        $lng1 = ($x1 * pi()) / 180;
        $lat2 = ($y2 * pi()) / 180;
        $lng2 = ($x2 * pi()) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }
}
